import axios from 'axios';
import qs from 'qs';

axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
axios.defaults.withCredentials = true;

axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// qs 将普通对象转换为`x-www-form-urlencoded`类型的数据
axios.defaults.transformRequest = data => qs.stringify(data);

// const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API,
//   // 跨域请求时发送Cookie
//   // withCredentials: true,
//   timeout: 5000
// })

// 前置
axios.interceptors.request.use(config => {
  if (false/* judge hasToken */) {
    config.headers['Authorization'] = 'getToken()'
  }
  return config
}, error => {
  // do something with request error
  console.log(error) // for debug
  return Promise.reject(error)
})

// 后置
axios.interceptors.response.use(response => {
  return response.data;
}, reason => {
  const reasonResponse = reason.response;
  if (reasonResponse) {
    switch (parseInt(reasonResponse.status)) {
      case 400:
        break;
      case 401:
        break;
      case 403:
        break;
      case 404:
        break;
    }
  } else {
    if (!window.navigator.onLine) {
      // 断网处理
    }
  }
  return Promise.reject(reason)
});

export default axios;